/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BAOpeningHoursViewController.m
//  redia-bapps-ios
//
//  Created by Mads Darø Kristensen on 10/7/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BAOpeningHoursViewController.h"
#import "BARPCManager.h"
#import "BAOpeningHoursLibrary.h"
#import "BAFlyoutMenuViewController.h"
#import "BAUtils.h"
#import "BAOpeningHoursDetailsViewController.h"
#import "BAOpeningHoursDay.h"
#import "BAOpeningHoursInterval.h"
#import "BAOpeningHoursLibraryCell.h"
#import "BAOpeningHoursTopLibraryCell.h"
#import "BASlideInViewController.h"
#import "BARootViewController.h"
#import "BALibrarySettings.h"
#import "InfoGalleriImageUrlUtils.h"

@interface BAOpeningHoursViewController ()

@property (strong, nonatomic) NSArray *libraries;
@property (strong, nonatomic) NSMutableArray *libraryCells;

@property (strong, nonatomic) BAOpeningHoursTopLibraryCell* topCell;
@property (strong, nonatomic) BAOpeningHoursDetailsViewController* currentDetailsControllerIPad;

@property (strong, nonatomic) NSDate* lastLoadedDate;
@end

@implementation BAOpeningHoursViewController

+(NSString*)getOpeningHoursResizedLogoUrl
{
    NSString* logo_url = [[BALibrarySettings instance] getLogoUrlStringForType:BALibrarySettingsLogoUrlTypeDefault];
    if (logo_url!=nil && [logo_url length]>0) {
        NSString* resizeurl = [InfoGalleriImageUrlUtils getResizedImageUrl:logo_url
                                                                   toWidth:290
                                                                  toHeight:97
                                                              usingQuality:9
                                                                  withMode:IMAGE_URL_UTILS_RESIZE_MODE_BOUNDING_BOX
                                                              outputFormat:@"png"
                                                         doubleUpForRetina:YES];
        return resizeurl;
    } else {
        return nil;
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _libraries = @[];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view from its nib.
    RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7
    BA_FLYOUT_MENU_ADD_BUTTON(BASpecialNavigationBarConfigurationDefault)

    self.librariesTableView.dataSource = self;
    self.librariesTableView.delegate = self;
    
    self.topCell = [[[NSBundle mainBundle] loadNibNamed:@"BAOpeningHoursTopLibraryCell" owner:self options:nil] objectAtIndex:0];

    if (RD_IS_IPAD) {
        self.viewDetailsShadowIPad.layer.shadowColor = [[UIColor blackColor] CGColor];
        self.viewDetailsShadowIPad.layer.shadowOpacity = 0.45;
        self.viewDetailsShadowIPad.layer.shadowRadius = 1.5;
        self.viewDetailsShadowIPad.layer.shadowOffset = CGSizeMake(-1.0f, 0.0f);
        self.viewDetailsShadowIPad.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.detailsViewIPad.bounds].CGPath;
    }
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receivedDidBecomeActiveNotification:)
                                                 name:BA_APP_DELEGATE_DID_BECOME_ACTIVE
                                               object:nil];

}

- (void)dealloc
{
    [BARPCManager closeConnectionsForView:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BA_APP_DELEGATE_DID_BECOME_ACTIVE object:nil];

}

- (void) receivedDidBecomeActiveNotification:(NSNotification*) notification
{
    [self refreshOpeningHoursIfNeeded];
}


- (void)viewDidAppear:(BOOL)animated
{
    if ([self.lastLoadedDate timeIntervalSinceNow]<-300) {
        //empty list after 5 minutes
        self.libraries=nil;
        self.libraryCells=nil;
        [self.librariesTableView reloadData];
        [self.activityIndicator startAnimating];
    }

    [super viewDidAppear:animated];
    
    [self refreshOpeningHours]; //allways refresh
}

-(void)refreshOpeningHours
{
    [self enableUserInteraction];

    self.lastLoadedDate = [NSDate date]; //avoid multiple concurrent calls

    [BARPCManager getOpeningHoursAsyncFromView:self
                                   resultBlock:^(NSArray *result) {
                                       [result sortedArrayUsingComparator:^NSComparisonResult(BAOpeningHoursLibrary *obj1, BAOpeningHoursLibrary *obj2) {
                                           if (obj1.priority > obj2.priority) {
                                               return NSOrderedAscending;
                                           }
                                           else if (obj1.priority < obj2.priority) {
                                               return NSOrderedDescending;
                                           }
                                           else {
                                               return NSOrderedSame;
                                           }
                                       }];
                                       self.libraries = result;
                                       [self createCells];
                                       self.lastLoadedDate = [NSDate date];
                                   }
                                    errorBlock:^(int errorCode, NSString *message) {
                                        [[[UIAlertView alloc] initWithTitle:@"Der opstod en fejl" message:@"Listen over ugens åbningstider kunne desværre ikke hentes. Prøv igen senere." delegate:nil cancelButtonTitle:@"Luk" otherButtonTitles:nil] show];
                                        DLog(@"Error fetching opening hours. Errorcode=%d, message=%@", errorCode, message);
                                        [self.activityIndicator stopAnimating];
                                        self.lastLoadedDate = nil;
                                    }];

}

-(void)refreshOpeningHoursIfNeeded
{
    if (self.lastLoadedDate==nil) {
        [self refreshOpeningHours];
    } else {
        if ([self.lastLoadedDate timeIntervalSinceNow] < -600) {
            [self refreshOpeningHours];
        }
    }
}

-(void)createCells
{
    
    self.libraryCells = [NSMutableArray new];
    
    for (int i=0; i<[self.libraries count]; i++) {
        BAOpeningHoursLibrary* lib = [self.libraries objectAtIndex:i];
        
        BAOpeningHoursLibraryCell* cell = [[[NSBundle mainBundle] loadNibNamed:@"BAOpeningHoursLibraryCell" owner:self options:nil] objectAtIndex:0];
        
        [cell setLibrary:lib lightBackground:(i%2 == 0)];
        [self.libraryCells addObject:cell];
        
    }
    
    [self.librariesTableView reloadData];
    [self.activityIndicator stopAnimating];
    
    
    if (RD_IS_IPAD) {
        if ([self.libraries count]>0) {
            [self.librariesTableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:1] animated:NO scrollPosition:UITableViewScrollPositionNone];
            
            self.currentDetailsControllerIPad = [[BAOpeningHoursDetailsViewController alloc] initWithNibName:@"BAOpeningHoursDetailsViewController" bundle:nil];
            self.currentDetailsControllerIPad.library = [self.libraries objectAtIndex:0];
            [self addChildViewController:self.currentDetailsControllerIPad];
            [self.detailsViewIPad addSubview:self.currentDetailsControllerIPad.view];
            [BAUtils setViewToFillParent:self.currentDetailsControllerIPad.view];
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - Table view

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2; //top cell resides in section 0
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        if (self.topCell!=nil) {
            return 1;
        } else {
            return 0;
        }
    } else {
        return [self.libraryCells count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return self.topCell;
    } else {
        BAOpeningHoursLibraryCell* cell = [self.libraryCells objectAtIndex:indexPath.row];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==1) {

        BAOpeningHoursDetailsViewController *newDetailsVC = [[BAOpeningHoursDetailsViewController alloc] initWithNibName:@"BAOpeningHoursDetailsViewController" bundle:nil];
        newDetailsVC.library = [self.libraries objectAtIndex:indexPath.row];
        
        if (!RD_IS_IPAD) {
            [self.navigationController pushViewController:newDetailsVC animated:YES];
            
        } else {
            //ipad
            
            CGRect newframe = self.detailsViewIPad.bounds;
            CGRect animframe = newframe;
            animframe.origin.x += animframe.size.width;
            
            [self addChildViewController:newDetailsVC];
            [self.detailsViewIPad addSubview:newDetailsVC.view];
            newDetailsVC.view.frame = animframe;
            
            CGRect oldDetailsAnimFrame = self.currentDetailsControllerIPad.view.frame;
            oldDetailsAnimFrame.origin.x -= 100;
            
            [UIView animateWithDuration:0.4
                             animations:^{
                                 self.currentDetailsControllerIPad.view.frame = oldDetailsAnimFrame;
                                 self.currentDetailsControllerIPad.view.alpha = 0;
                                 newDetailsVC.view.frame = newframe;
                             }
                             completion:^(BOOL finished) {
                                 //remove old details view
                                 [self.currentDetailsControllerIPad.view removeFromSuperview];
                                 [self.currentDetailsControllerIPad removeFromParentViewController];
                                 self.currentDetailsControllerIPad=nil;
                                 
                                 //store new details view
                                 self.currentDetailsControllerIPad=newDetailsVC;
                             }];
            
            /* was:
            BASlideInViewController *slideIn = [BASlideInViewController findSlideInViewController:self];
            if (slideIn != nil) {
                [slideIn slideInViewController:detailsVC animated:NO completion:nil];
            }*/
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 127;
    } else {
        return 49;
    }
}

#pragma mark - Flyout menu

BA_FLYOUT_MENU_ADD_CALLBACK

- (void)enableUserInteraction
{
    self.view.userInteractionEnabled = YES;
    self.tabBarController.tabBar.userInteractionEnabled = YES;
}

- (void)disableUserInteraction
{
    self.view.userInteractionEnabled = NO;
    self.tabBarController.tabBar.userInteractionEnabled = NO;
}

@end
